package com.zretc.file.service;

import com.zretc.api.pojo.File;
import com.zretc.api.pojo.User;
import com.zretc.common.constant.WebConstant;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import com.zretc.file.config.MinioConfig;
import com.zretc.file.dao.FileMapper;
import com.zretc.file.util.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Objects;

@Service
public class FileService {
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient minioClient;

    @Resource
    private FileMapper fileMapper;

    public File getFileById(Integer resourceId){
        return fileMapper.getFileById(resourceId);
    }

    public RespResult getAllFile(){
        return R.success(fileMapper.getAllFile());
    }

    public RespResult getAllFileByName(String resourceName){
        return R.success(fileMapper.getAllFileByName(resourceName));
    }

    public RespResult getFileByUploader(Integer userId){
        if(Objects.isNull(userId))
        {
            return R.fail(WebConstant.NO_USER_ERROR_CODE, WebConstant.ERROR_301);
        }
        return R.success(fileMapper.getMyFile(userId));
    }

    public RespResult getFileByName(Integer userId, String resourceName){
        if(Objects.isNull(userId))
        {
            return R.fail(WebConstant.NO_USER_ERROR_CODE, WebConstant.ERROR_301);
        }
        //resourceName = "%" + resourceName + "%";
        return R.success(fileMapper.getMyFileByName(userId, resourceName));
    }

    public String[] upload(int bucketId, MultipartFile file) throws IOException, ServerException,
            InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException,
            InvalidResponseException, XmlParserException, InternalException {

        if(bucketId >= minioConfig.getBucketName().length){
            return null;
        }

        String[] fileStr = new String[3];

        // 随机生成文件名
        String filename = FileUploadUtils.extractFileName(file);
        fileStr[2] = filename;


        @Cleanup
        InputStream is = file.getInputStream(); // 所以二进制文件必须通过输入输出流来实现
        // 所有文件在minio里都算作对象
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName()[bucketId]) // 桶名
                .object(filename) // 文件名
                .stream(is, file.getSize(), -1)
                .contentType(file.getContentType())
                .build(); // 构建出了一个minio对象
        minioClient.putObject(args);
        StringBuilder finalFileName = new StringBuilder("http://192.168.33.15:9000");
        finalFileName.append("/").append(minioConfig.getBucketName()[bucketId]).append("/").append(filename); // 完整文件名

        fileStr[0] = finalFileName.toString();
        fileStr[1] = minioConfig.getBucketName()[bucketId];

        return fileStr;
    }

    public RespResult addFile(File fileInfo, String url, String bucketName, String randomFileName){
        System.out.println("FileService-------------------------------------------------------------------------------"); //test

        if(Objects.isNull(fileInfo.getResourceName())){
            return R.fail(405, WebConstant.ERROR_405);
        }
        else
        {
            fileInfo.setAddressMinio(url);
            fileInfo.setBucketName(bucketName);
            fileInfo.setObjectName(randomFileName);

            System.out.println(fileInfo); // test

            fileMapper.addFile(fileInfo);
            return R.success("上传成功");
        }
    }

    public RespResult remove(File file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        System.out.println(file.getResourceId()); // test

        File fileInfo = fileMapper.getFileById(file.getResourceId());

        if(Objects.isNull(fileInfo)){
            return R.fail(404, WebConstant.ERROR_404);
        }

        System.out.println("FileService==============================================================================="); // test
        System.out.println(fileInfo.getBucketName());
        System.out.println(fileInfo.getObjectName());

        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(fileInfo.getBucketName())
                .object(fileInfo.getObjectName())
                .build());

        fileMapper.removeFile(fileInfo);

        return R.success("删除成功");
    }

}
